﻿/*
Copyright (c) 2010, hiSoft
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the hiSoft nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE HISOFT AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL HISOFT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/

using System;
using System.Collections.Generic;

namespace Orchard.Test.Library
{
    public class SettingHelp : UIHelperBase
    {
        public SettingHelp(TestLibrary settings) : base(settings) { }       

        public void ManageGeneralSettings()
        {
            if (!selenium.GetLocation().EndsWith("Admin/Settings/Index"))
            {
                selenium.Open("/Admin/Settings/Index");
            }
        }     

        private bool IsCultureAdded(string cultureName)
        {
            var siteCulturesCount = (int)selenium.GetXpathCount(SiteCulturesLocator);           
            for (int index = 1; index <= siteCulturesCount; index++)
            {
                string siteCulture = null;
                if (selenium.IsElementPresent(String.Format("{0}[{1}]/strong", SiteCulturesLocator, index)))
                {
                    siteCulture = selenium.GetText(String.Format("{0}[{1}]/strong", SiteCulturesLocator, index));
                }
                else
                {
                    string siteCultureStr = selenium.GetText(String.Format("{0}[{1}]/div", SiteCulturesLocator, index));
                    siteCulture = siteCultureStr.Substring(0, siteCultureStr.Length - 2);
                }
                if (siteCulture == cultureName)
                {
                    return true;
                }
            }
            return false;
        }

        public void AddCulture(string cultureName)
        {
            selenium.Open("/Admin/Settings/Culture");
            string cultureOptionLocators = "//select[@id='SystemCultureName']/option";
            var systemCultureOptionCount = (int)selenium.GetXpathCount(cultureOptionLocators);
            int i = 1;
            for (; i <= systemCultureOptionCount; i++)
            {
                if (selenium.GetText(String.Format("{0}[{1}]", cultureOptionLocators,i)) == cultureName)
                {
                    selenium.Select("SystemCultureName", String.Format("label={0}", cultureName));
                    break;
                }
            }
            if (i > systemCultureOptionCount)
            {
                selenium.Type("CultureName", cultureName);
            }
            Submit();                     
        }

        public void RemoveCulture(string cultureName)
        {
            selenium.Open("/Admin/Settings/Culture");
            if (IsCultureAdded(cultureName))
            { 
                var count = (int)selenium.GetXpathCount(SiteCulturesLocator);
                for (int index = 1; index <= count; index++)
                {
                    string cultureLocator = String.Format("{0}[{1}]/div", SiteCulturesLocator, index);
    
                    if (selenium.IsElementPresent(cultureLocator))
                    {
                        var siteCultureStr = selenium.GetText(cultureLocator);
                        string siteCulture = siteCultureStr.Substring(0, siteCultureStr.Length - 2);
                        if (String.CompareOrdinal(cultureName, siteCulture) == 0)
                        {
                            ClickAndWait(String.Format("{0}[{1}]/div/a", SiteCulturesLocator, index));
                        }
                    }
                }
            }
        }

        public int GetSiteCulturesCount()
        {
            selenium.Open("/Admin/Settings/Culture");
            return (int)selenium.GetXpathCount("//ul[@class='site-cultures']/li");
        }

        public void ChangeSiteName(string newSiteName)
        {
            ManageGeneralSettings();
            selenium.Type("SiteSettings_SiteName", newSiteName);
            Submit();
        }

        public void ChangeDefaultSiteCultrue(string cultrueName)
        {
            ManageGeneralSettings();
            selenium.Select("SiteSettings_SiteCulture", String.Format("label={0}", cultrueName));
            Submit();          
        }

        public void ChangePageTitleSeparator(string separator)
        {
            ManageGeneralSettings();
            selenium.Type("SiteSettings_PageTitleSeparator", separator);
            Submit();
        }

        public void ChangeSuperUser(string userName)
        {
            ManageGeneralSettings();
            selenium.Type("SiteSettings_SuperUser", userName);
            Submit();
        }

        public void ConfigurePageSize(string pageSize)
        {
            ManageGeneralSettings();
            selenium.Type("SiteSettings_PageSize", pageSize);
            Submit();
        }

        public void ConfigureBaseUrl(string baseUrl)
        {
            ManageGeneralSettings();
            selenium.Type("SiteSettings_BaseUrl", baseUrl);
            //Submit();
            selenium.Click("//button[@type='submit']");
            selenium.WaitForPageToLoad("90000");
        }
               
        public void ConfigureMessagingSettings(string defaultChannelService)
        {
            ManageGeneralSettings();
            selenium.Select("MessageSettings_MessageSettings_DefaultChannelService", defaultChannelService);
            Submit();
        }

        public void ConfigureUsersSettings(bool usersCanRegister, bool enableLostPassword, bool usersMustValidateEmail, string validateEmailRegisteredWebsite, string validateEmailContactEmail, bool usersAreModerated, bool notifyModeration, string notificationsRecipients)
        {
            selenium.Open("/Admin/Settings/Users");
            string usersCanRegisterLocator = "RegistrationSettings_UsersCanRegister";
            string enableLostPasswordLocator = "RegistrationSettings_EnableLostPassword";
            string usersMustValidateEmailLocator = "RegistrationSettings_UsersMustValidateEmail";
            string validateEmailRegisteredWebsiteLocator = "RegistrationSettings_ValidateEmailRegisteredWebsite";
            string validateEmailContactEmailLocator = "RegistrationSettings_ValidateEmailContactEMail";
            string usersAreModeratedLocator = "RegistrationSettings_UsersAreModerated";
            string notifyModerationLocator = "RegistrationSettings_NotifyModeration";
            string notificationsRecipientsLocator = "RegistrationSettings_NotificationsRecipients";

            if (usersCanRegister)
            {
                selenium.Check(usersCanRegisterLocator);
            }
            else
            {
                selenium.Uncheck(usersCanRegisterLocator);
            }

            if (enableLostPassword)
            {
                selenium.Check(enableLostPasswordLocator);
            }
            else
            {
                selenium.Uncheck(enableLostPasswordLocator);
            }

            if (usersMustValidateEmail)
            {
                selenium.Check(usersMustValidateEmailLocator);
                selenium.Type(validateEmailRegisteredWebsiteLocator, validateEmailRegisteredWebsite);
                selenium.Type(validateEmailContactEmailLocator, validateEmailContactEmail);
            }
            else
            {
                selenium.Uncheck(usersMustValidateEmailLocator);
            }

            if (usersAreModerated)
            {
                selenium.Check(usersAreModeratedLocator);
                if (notifyModeration)
                {
                    selenium.Check(notifyModerationLocator);
                    selenium.Type(notificationsRecipientsLocator, notificationsRecipients);
                }
                else
                {
                    selenium.Uncheck(notifyModerationLocator);
                }
            }
            else
            {
                if (selenium.GetValue(usersAreModeratedLocator) == "on")
                {
                    if (selenium.GetValue(notifyModerationLocator) == "on")
                    {
                        selenium.Uncheck(notifyModerationLocator);
                    }
                    selenium.Uncheck(usersAreModeratedLocator);
                }
            }

            Submit();
        }

        public void ConfigureCommentsSettings(bool approveBeforeAppear, bool enableSpamProtection, string akismetKey, string akismetUrl)
        {
            selenium.Open("/Admin/Settings/Comments");
            string moderateCommentsLocator = "CommentSettings_ModerateComments";
            string enableSpamProtectionLocator = "CommentSettings_EnableSpamProtection";

            if (approveBeforeAppear)
            {
                selenium.Check(moderateCommentsLocator);
            }
            else
            {
                selenium.Uncheck(moderateCommentsLocator);
            }

            if (enableSpamProtection)
            {
                selenium.Check(enableSpamProtectionLocator);
                selenium.Type("CommentSettings_AkismetKey", akismetKey);
                selenium.Type("CommentSettings_AkismetUrl", akismetUrl);
            }
            else
            {
                selenium.Uncheck(enableSpamProtectionLocator);
            }

            Submit();
        }

        public void ConfigureSearchSettings(List<string> searchIndexes)
        {
            selenium.Open("/Admin/Settings/Search");
            string seachIndexesLocator = "//form[@action='/Admin/Settings/Search']/fieldset/div/ul/li";
            var searchIndexesCount = (int)selenium.GetXpathCount(seachIndexesLocator);
            for (int searchIndex = 1; searchIndex <= searchIndexesCount; searchIndex ++)
            {
                string searchIndexName = selenium.GetText(String.Format("{0}[{1}]/label", seachIndexesLocator, searchIndex));
                string searchIndexCheckboxLocator = String.Format("{0}[{1}]/input", seachIndexesLocator, searchIndex);
                if (searchIndexes != null && searchIndexes.Contains(searchIndexName))
                {
                    selenium.Check(searchIndexCheckboxLocator);
                }
                else
                {
                    selenium.Uncheck(searchIndexCheckboxLocator);
                }
            }
            Submit();
        }

        public void ConfigureSmtpSettingsByDefault()
        {
            ConfigureSmtpSettings(TestLibrary.Consts.strSenderEmailAddOf163, TestLibrary.Consts.strEmailSMTPHostOf163, "25", false, true, TestLibrary.Consts.strSenderUserNameOf163, TestLibrary.Consts.strSenderEamilPwdOf163);
        }

        public void ConfigureSmtpSettings(string senderEmail, string hostName, string portNumber, bool enableSsl, bool requireCredentials, string userName, string password)
        {
            selenium.Open("/Admin/Settings/Email");
            string enableSslLocator = "SmtpSettings_EnableSsl";
            string requireCredentialsLocator = "SmtpSettings_RequireCredentials";

            selenium.Type("SmtpSettings_Address", senderEmail);
            selenium.Type("SmtpSettings_Host", hostName);
            selenium.Type("SmtpSettings_Port", portNumber);

            if (enableSsl)
            {
                selenium.Check(enableSslLocator);
            }
            else
            {
                selenium.Uncheck(enableSslLocator);
            }

            if (requireCredentials)
            {
                selenium.Check(requireCredentialsLocator);
                selenium.Type("SmtpSettings_UserName", userName);
                selenium.Type("SmtpSettings_Password", password);
            }
            else
            {
                selenium.Uncheck(requireCredentialsLocator);
            }

            Submit();
        }

        public void ConfigureMailSettings(string smtpAddress,string hostName,string portNum,bool enableSSl,bool requireCredential,string userName,string password)
        {
            selenium.Open("/Admin/Settings/Email");
            selenium.Type("SmtpSettings_Address",smtpAddress);
            selenium.Type("SmtpSettings_Host",hostName);
            selenium.Type("SmtpSettings_Port", portNum);
            selenium.Check("SmtpSettings_EnableSsl");
            selenium.Check("SmtpSettings_RequireCredentials");
            selenium.Type("SmtpSettings_UserName",userName);
            selenium.Type("SmtpSettings_Password",password);
            Submit();
        }

        public void ConfigureMediaSettings(string uploadAllowedFileTypes)
        {
            selenium.Open("/Admin/Settings/Media");
            selenium.Type("MediaSettings_UploadAllowedFileTypeWhitelist", uploadAllowedFileTypes);
            Submit();
        }

        public void ConfigureMediaSettingsByDeleteSpecialType(string deleteFileType)
        {
            string allowTypes = GetMediaSettingsAllowTypes();
            allowTypes = allowTypes.Replace(deleteFileType, "");
            selenium.Type("MediaSettings_UploadAllowedFileTypeWhitelist", allowTypes);
            Submit();
        }

        public string GetMediaSettingsAllowTypes()
        {
            selenium.Open("/Admin/Settings/Media");
            return selenium.GetAttribute("//input[@id='MediaSettings_UploadAllowedFileTypeWhitelist']@value");
        }

        public void ConfigureWarmup(string urls, bool scheduled, string delay, bool onPublish, SubmitAction submitAction)
        {
            selenium.Open("/Admin/Warmup");

            selenium.Type("Settings_Urls", urls);
            if (scheduled)
            {
                selenium.Check("Settings_Scheduled");
                selenium.Type("Settings_Delay", delay);
            }
            else
            {
                selenium.Uncheck("Settings_Scheduled");
            }
            if (onPublish)
            {
                selenium.Check("Settings_OnPublish");
            }
            else
            {
                selenium.Uncheck("Settings_OnPublish");
            }
            switch (submitAction)
            {
                case SubmitAction.Save:
                    ClickAndWait("//button[@name='submit']");
                    break;
                case SubmitAction.Generate:
                    ClickAndWait("//button[@name='submit.Generate']");
                    break;
                case SubmitAction.Extract:
                    ClickAndWait("//button[@name='submit.Extract']");
                    break;
            }
        }



    }

    public enum SubmitAction
    {
        Save,
        Generate,
        Extract
    }
}
